
/**
 * 1. 必须要获取到 state -> reduce(state, action)
 * 2. 必须知道 reducer 执行了并且 state 变化 -> 
 *      reduce() -> new state -> 存储在哪里
 *                    subscribe -> cb
 *                                      
 */
const redux = { /** _state  */ }
const cbs = []


export function createStore(reducer) {
    createReduxState(reducer)
    const dispatch = createDispatcher(reducer)
    const getState = createStateGetter(reducer)


    return {
        dispatch,
        getState,
        subscribe
    }
}

function createReduxState (reducer) {
    let _state = reducer()

    Object.defineProperty(redux, '_state', {
        get () {
            return _state
        },
        set(newValue) {
            if(_state === newValue)
                return
            _state = newValue
            // subscribe -> cb
            publish()
        }
    })

}

function subscribe(cb) {
    if(cbs.includes(cb)) return
    cbs.push(cb)
}

function publish() {
    cbs.forEach(cb => cb())
}

function createDispatcher(reducer) {
    return function (action) {
        redux._state = reducer(reducer._state, action)
    }
}

function createStateGetter(reducer) {
    return function () {
        return reducer(reducer._state)
    }
}